package com.woniuxy.springparking.asepct;

import com.woniuxy.springparking.pojo.Log;
import com.woniuxy.springparking.pojo.User;
import com.woniuxy.springparking.service.LogService;
import com.woniuxy.springparking.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;

    @AfterReturning("@annotation(sysLog)")
    public void saveLog (JoinPoint joinPoint,SysLog sysLog){
        Log log=new Log();
       String username= (String) SecurityUtils.getSubject().getPrincipal();
        String rename=userService.findReaNameByUserName(username);
        log.setUser(rename);
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        log.setIp(request.getRemoteHost());
        log.setCreatetime(new Date());
        log.setBody(sysLog.value2());
        log.setType(sysLog.value1());
        log.setResult("成功");
        logService.insertLog(log);

    }
}
